package com.wf.handler;

import com.alibaba.fastjson.JSON;
import com.wf.dao.pojo.SysUser;
import com.wf.service.LoginService;
import com.wf.utils.UserThreadLocal;
import com.wf.vo.ErrorCode;
import com.wf.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean flag = true;

        //测试使用，临时固定已登录用户
//        SysUser sysUser = new SysUser();
//        sysUser.setId(14);
//        log.info(sysUser.getId()+"被放入线程池");
//        UserThreadLocal.put(sysUser);

        //正常验证登录使用
        flag = checkLogin(handler,request, response);
        return flag;
    }

    private boolean checkLogin(Object handler,HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        if (token == null){
            log.info("未在Header中接收到token");
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        //已登录，用将登录 token 中的信息封装为 SysUser
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null){
            log.info("未找到对应sysUser");
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), "未登录");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //是登录状态，放行,并放入线程池
        log.info(sysUser.getNickname()+"被放入线程池");
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info(UserThreadLocal.get().getNickname()+"从线程池中移除");
        UserThreadLocal.remove();
    }

}
